﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
using System.Web.Routing;

namespace CloverNet.Authorization
{
    public static class AuthorizationManager
    {
        /// <summary>
        /// 无权访问重定向地址
        /// </summary>
        public static Func<HttpContextBase, ActionResult> UnAuthenticationAction { get; set; }

        /// <summary>
        /// 用户登录储存Key值
        /// </summary>
        public static string UserLoginStorageKey { get; set; } = "UserLoginStorageKey";

        /// <summary>
        /// 用户权限储存Key值
        /// </summary>
        public static string UserAuthStorageKey { get; set; } = "UserAuthStorageKey";

        /// <summary>
        /// 是否已登录
        /// </summary>
        public static bool IsLogIn
        {
            get => DefaultStorageProvider.Current.GetValue(UserLoginStorageKey) != null;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        public static void LogIn(dynamic model)
        {
            UserModel = model;
            DefaultStorageProvider.Current.SetValue(UserLoginStorageKey, model);

            //写入用户权限
            DefaultStorageProvider.Current.SetValue(UserAuthStorageKey, PermissionProviders.Providers.GetPermissions());
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="model"></param>
        public static void LogOut()
        {
            UserModel = null;
            DefaultStorageProvider.Current.SetValue(UserLoginStorageKey, null);

            //清除用户权限
            DefaultStorageProvider.Current.SetValue(UserAuthStorageKey, null);
        }

        public static dynamic UserModel { get; private set; }
    }
}
